package starfire.gui.defaultModelAndRenderer;

import java.io.*;
import java.text.*;
import java.util.*;

import javax.swing.table.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author zzzhc.starfire@gmail.com
 * @version 1.0
 */

public class DefaultFSTableModel
    extends javax.swing.table.DefaultTableModel {
  File dir = null;
  public static String[] headers = {
      "Name", "Date", "Time", "Length"};
  public static int NAMECOLUMN = 0;
  public static int DATECOLUMN = 1;
  public static int TIMECOLUMN = 2;
  public static int LENGTHCOLUMN = 3;

  public DefaultFSTableModel(File dir) {
    super(headers, headers.length);
    this.dir = dir;
    addSubFile(dir);
  }

  protected void addSubFile(File dir) {
    if (!dir.exists() || dir.isFile()) {
      return;
    }
    File[] fs = dir.listFiles();
    dataVector.clear();
    for (int i = 0; i < fs.length; i++) {
      if (fs[i].exists() && !fs[i].isHidden() && fs[i].isDirectory()) {
        dataVector.add(fs[i]);
      }
    }
    for (int i = 0; i < fs.length; i++) {
      if (fs[i].exists() && !fs[i].isHidden() && fs[i].isFile()) {
        dataVector.add(fs[i]);
      }
    }
  }

  public String getColumnName(int column) {
    if (column < headers.length) {
      return headers[column];
    }
    return null;
  }

  public Class getColumnClass(int columnIndex) {
    if (columnIndex == NAMECOLUMN) {
      return File.class;
    }
    if (columnIndex == DATECOLUMN) {
      return String.class;
    }
    if (columnIndex == TIMECOLUMN) {
      return String.class;
    }
    if (columnIndex == LENGTHCOLUMN) {
      return Long.class;
    }
    return String.class;
  }

  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
  }

  public Object getValueAt(int rowIndex, int columnIndex) {
    File f = (File) dataVector.get(rowIndex);
    if (f == null) {
      return null;
    }
    if (columnIndex == NAMECOLUMN) {
      return f;
    }
    if (columnIndex == DATECOLUMN) {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      Date date = new Date(f.lastModified());
      return formatter.format(date);
    }
    if (columnIndex == TIMECOLUMN) {
      SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
      Date date = new Date(f.lastModified());
      return formatter.format(date);
    }
    if (columnIndex == LENGTHCOLUMN) {
      return new Long(f.length());
    }
    return null;
  }

  public void setValueAt(Object aValue, int row, int column) {
    if (column != 0) {
      return;
    }
    File f = (File) dataVector.elementAt(row);
    File temp = new File(f.getParent() + f.separatorChar +
                         ( (File) aValue).getName());
    f.renameTo(temp);
    dataVector.set(row, temp);
  }
}
